import type { RouterContext } from "@koa/router";
import { BaseController } from "./common";
import { JWTPayload } from "@/services/vendor/jsonwebtoken";
import { container } from "@/services/register";
import {
  CreateLcPageRequest,
  GetLcPageListByPageRequest,
  UpdateLcPageRequest,
} from "@/types/api";
import { empty, isset } from "@/utils/validator";
import { Prisma } from "@prisma/generated-client";

export default class LcPageController extends BaseController {
  typeValidator(type: number) {
    return [0, 1].includes(type);
  }
  statusValidator(status: number) {
    return [0, 1, 2].includes(status);
  }
  async insert(ctx: RouterContext) {
    const user = this.getUser<JWTPayload>(ctx);
    const body = this.getBody<CreateLcPageRequest>(ctx);
    this.assert(
      isset(body?.type) && this.typeValidator(body.type),
      1,
      "type error"
    );
    this.assert(!empty(body?.title), 2, "title error");
    return container.resolve("LcPageService").create({
      userId: user.userId,
      type: body.type,
      title: body.title,
      remark: body.remark || "",
      blocks: body.blocks || "",
    });
  }
  async remove(ctx: RouterContext) {
    const params = this.getParams<{ id: string }>(ctx);
    return container.resolve("LcPageService").delete(+params.id);
  }
  async patch(ctx: RouterContext) {
    const params = this.getParams<{ id: string }>(ctx);
    const body = this.getBody<UpdateLcPageRequest>(ctx);
    const data: Prisma.LcPageUncheckedUpdateInput = {};
    if (isset(body?.type) && this.typeValidator(body.type)) {
      data.type = Number(body.type);
    }
    if (isset(body?.title)) {
      data.title = String(body.title);
    }
    if (isset(body?.remark)) {
      data.remark = String(body.remark);
    }
    if (isset(body?.status) && this.statusValidator(body.status)) {
      data.status = Number(body.status);
    }
    if (isset(body?.reason)) {
      data.reason = String(body.reason);
    }
    if (isset(body?.blocks)) {
      data.blocks = String(body.blocks);
    }
    return container.resolve("LcPageService").update(+params.id, data);
  }
  async put(ctx: RouterContext) {
    return this.patch(ctx);
  }
  async get(ctx: RouterContext) {
    const params = this.getParams<{ id: string }>(ctx);
    return container.resolve("LcPageService").findOne(+params.id);
  }
  async page(ctx: RouterContext) {
    const query = this.getQuery<GetLcPageListByPageRequest>(ctx);
    const page = Number(query?.page);
    const size = Number(query?.size);
    this.assert(isset(page) && page > 0, 1, "page error");
    this.assert(isset(size) && size > 0 && size < 1000, 2, "size error");
    return container.resolve("LcPageService").page(page, size, query.keywords);
  }
}
